import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
    Row,
    Col,
    Card,
    Form,
    Button,
    DatePicker,
    message,
    Divider,
    Badge,
    Table,
    Input,
    Select,
    Popconfirm,
} from 'antd';
import { getAccess } from '@/utils/accessFunctions';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import UpdataModel from './otaUpdataModel';
import styles from './otaUpdata.less';

const Option = Select.Option;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;

const statusMap = ['success', 'error'];
const status = ['已启用', '未启用'];

/* eslint react/no-multi-comp:0 */
@connect(({ loading, obd, menuTree }) => ({
    obd,
    loading: loading.models.obd,
    menuTree: menuTree.menuData,
}))
@Form.create()
class TableList extends PureComponent {
    state = {
        access: {},
        formValues: {
            page: '1',
            pageSize: '10',
        },
        modalVisible: false,
        modalValues: {},
    };

    columns = [
        {
            title: '序号',
            render: (text, record, index) => `${index + 1}`,
            key: 'index',
        },
        {
            title: '升级包名称',
            dataIndex: 'packageName',
            key: 'packageName'
        },
        {
            title: '升级包版本',
            dataIndex: 'version',
            key: 'version'
        },
        {
            title: '修改时间',
            dataIndex: 'uploadTime',
            key: 'uploadTime',
        },
        {
            title: '操作',
            render: record => (
                <Fragment>
                    {/* {this.state.access &&
                        Object.keys(this.state.access).length &&
                        this.state.access.hasOwnProperty('updateSimCard') ? (
                            <Fragment>
                                <a onClick={() => this.handleModalVisible(true, record)}>
                                    {this.state.access.updateSimCard.name}
                                </a>
                                <Divider type="vertical" />
                            </Fragment>
                        ) : null}
                    {this.state.access &&
                        Object.keys(this.state.access).length &&
                        this.state.access.hasOwnProperty('deleteSimCard') ? (
                            <Popconfirm
                                title="确定删除该选项么?"
                                onConfirm={() => this.popConfirm(record)}
                                onCancel={() => { }}
                                okText="Yes"
                                cancelText="No"
                            >
                                <a>{this.state.access.deleteSimCard.name}</a>
                            </Popconfirm>
                        ) : null} */}
                    <a onClick={() => this.handleModalVisible(true,record)}>
                       修改
                    </a>
                    <Divider type="vertical" />
                    <a>
                        删除
                    </a>
                </Fragment>
            ),
        },
    ];

    componentDidMount() {
        const {
            dispatch,
            location: { pathname },
            menuTree,
        } = this.props;
        const { formValues } = this.state;
        dispatch({
            type: 'obd/fetchQueryPackageList',
            payload: formValues,
        });

        const access = getAccess(pathname, menuTree);
        this.setState({
            access: access.childMap || {},
        });
    }
    // 分页change
    handleStandardTableChange = (pagination, filtersArg, sorter) => {
        const { dispatch } = this.props;
        const { formValues } = this.state;

        const params = {
            ...formValues,
            page: pagination.current,
            pageSize: pagination.pageSize,
        };
        this.setState({
            formValues: params,
        });

        dispatch({
            type: 'obd/fetchQueryPackageList',
            payload: params,
        });
    };
    // 查询
    handleSearch = e => {
        e.preventDefault();

        const { dispatch, form } = this.props;
        const { formValues } = this.state;

        form.validateFields((err, fieldsValue) => {
            if (err) return;
            let values = null;

            var rangeValue = fieldsValue['chooseTime'];
            if (rangeValue !== undefined && rangeValue.length !== 0) {
                rangeValue = [
                    rangeValue[0].format('YYYY-MM-DD') + " 00:00:00",
                    rangeValue[1].format('YYYY-MM-DD') + " 23:59:59",
                ];
            } else {
                rangeValue = ['', ''];
            }
            values = {
                ...formValues,
                startTime: rangeValue[0],
                endTime: rangeValue[1],
                page: 1
            };

            this.setState({
                formValues: values,
            });
            dispatch({
                type: 'obd/fetchQueryPackageList',
                payload: values,
            });
        });
    };
    // 新增和编辑
    handleModalVisible = (flag, record) => {
        this.setState({
            modalVisible: !!flag,
            modalValues: record || {},
        });
    };
    // 新增和编辑---submit
    handleSubmit = fields => {
        const { dispatch } = this.props;
        const { formValues } = this.state;
        console.log(fields)
        if (fields.hasOwnProperty('id')) {//修改
            dispatch({
                type: 'obd/fetchUpdatePackageInfo',
                payload: fields,
                callback: res => {
                    if (res.code !== '000000') message.warning(res.msg);
                    if (res.code === '000000') message.success('修改成功！！');
                    this.handleModalVisible();
                    dispatch({
                        type: 'obd/fetchQueryPackageList',
                        payload: formValues,
                    });
                },
            });
        } else {//新增
            dispatch({
                type: 'obd/fetchAddUpdatePackage',
                payload: fields,
                callback: res => {
                    if (res.code !== '000000') message.warning(res.msg);
                    if (res.code === '000000') message.success('添加成功！！');
                    this.handleModalVisible();
                    dispatch({
                        type: 'obd/fetchQueryPackageList',
                        payload: formValues,
                    });
                },
            });
        }
    };
    renderOTAForm() {
        const {
            form: { getFieldDecorator },
        } = this.props;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={8} sm={24}>
                        <FormItem label="选择时间">
                            {getFieldDecorator('chooseTime', {})(
                                <RangePicker
                                    allowClear
                                    format="YYYY-MM-DD"
                                    style={{ width: '100%' }}
                                />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <span className={styles.submitButtons}>
                            {/* {this.state.access &&
                                Object.keys(this.state.access).length &&
                                this.state.access.hasOwnProperty('querySimCard') ? (
                                    <Button type="primary" htmlType="submit">
                                        {this.state.access.querySimCard.name}
                                    </Button>
                                ) : null} */}
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                        </span>
                    </Col>
                </Row>
            </Form>
        );
    }
    popConfirm(record) {
        const { dispatch } = this.props;
        let keys = new Array();
        keys.push(record.id);
        dispatch({
            type: 'obd/fetchDeleteSimCard',
            payload: { allKeys: keys },
            callback: res => {
                const { formValues } = this.state;
                dispatch({
                    type: 'obd/fetchQuerySimCard',
                    payload: formValues,
                });
            },
        });
    }
    render() {
        const {
            obd: { packageList },
            loading,
        } = this.props;
        const { modalVisible, modalValues, access } = this.state;
        // 新建
        const handleMethods = {
            handleSubmit: this.handleSubmit,
            handleModalVisible: this.handleModalVisible,
        };
        // console.log(access);
        return (
            <PageHeaderWrapper  Breadcrumb>
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>{this.renderOTAForm()}</div>
                        <div className={styles.tableListOperator}>
                            {/* {access && Object.keys(access).length && access.hasOwnProperty('addSimCard') ? (
                                <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                                    {access.addSimCard.name}
                                </Button>
                            ) : null} */}
                            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                                新增
                            </Button>
                        </div>
                        <div className={styles.tableList}>
                            <Table
                                loading={loading}
                                dataSource={packageList.list}
                                columns={this.columns}
                                pagination={packageList.pagination}
                                onChange={this.handleStandardTableChange}
                                rowKey={record => record.id}
                            />
                        </div>
                    </div>
                </Card>
                <UpdataModel {...handleMethods} modalVisible={modalVisible} modalValues={modalValues} />
            </PageHeaderWrapper>
        );
    }
}

export default TableList;
